package com.taotao.manage.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.manage.pojo.Item;
import com.taotao.manage.pojo.ItemDesc;

@Service
public class ItemService extends BaseService<Item> {
	
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private ItemDescService itemDescService;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();

	public Boolean saveItemAndDesc(Item item, String desc) {
		// 新增商品
		item.setId(null);
		item.setStatus(1);
		int count1 = super.saveSelective(item);

		// 新增描述
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemDesc(desc);
		itemDesc.setItemId(item.getId());
		int count2 = this.itemDescService.saveSelective(itemDesc);
		
		sendMsg(item, "insert");
		
		return count1 == 1 && count2 == 1;
	}

	/**
	 * 更新商品及商品描述
	 * 
	 * @param item
	 * @param desc
	 * @return
	 */
	public Boolean updateItemAndDesc(Item item, String desc) {
		// 更新商品
		item.setStatus(null);
		int count1 = super.updateSelective(item);

		// 更新商品描述
		ItemDesc itemDesc = new ItemDesc();
		itemDesc.setItemDesc(desc);
		itemDesc.setItemId(item.getId());
		int count2 = this.itemDescService.updateSelective(itemDesc);
		
		sendMsg(item, "update");

		return count1 == 1 && count2 == 1;
	}
	
	private void sendMsg(Item item, String routingKey) {
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("routingKey", routingKey);
			map.put("id", item.getId());
			map.put("tiem", System.currentTimeMillis());
			
			this.rabbitTemplate.convertAndSend("item." + routingKey, MAPPER.writeValueAsString(map));
		} catch (AmqpException | JsonProcessingException e) {
			e.printStackTrace();
		}
	}

}
